package com.netspider.downloader;

import java.util.logging.Level;

import com.netspider.utils.Log;

public class Downloader 
{
	public Downloader(int id)
	{
		idle = true;
		this.id = id;
		Log.getLogger().log(Level.FINE, "[DLScheduler]downloader[" + id + "] have been create");
	}
	//Downloader
	public boolean isIdle()
	{
		return idle;
	}
	
	public int getID()
	{
		return this.id;
	}
	
	public void doTask(URL url)
	{
		if(!idle)
		{
			return;
		}
		this.url = url;
		idle = false;
		downloadthread = new Thread(new DLWorker());
		downloadthread.start();
		
		Log.getLogger().log(Level.FINE, "[DLScheduler]downloader[" + id + "] will begin to do task");
		
	}
	
	private void startWork()
	{
		try
		{
			Thread.sleep(id*100 + 1);
		}
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private class DLWorker implements Runnable
	{

		@Override
		public void run()
		{
			Log.getLogger().log(Level.FINE, "[DLScheduler]downloader[" + id + "] run");
			Downloader.this.startWork();
			Downloader.this.idle = true;
		}
		
	}
	
	private boolean idle;
	private int id;
	private URL url;
	private Thread downloadthread;
}
